package com.leozhang.app;

import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.List;

public class ServerCert {
    public static void main(String[] args) {
        String httpsUrl = " https://10.40.0.2/"; // 替换为目标 HTTPS 地址
        try {
            URL url = new URL(httpsUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setHostnameVerifier((hostname, session) -> {
                System.out.println("hostname: " + hostname + ", session: " + session);
                String privateIPPattern = "^(10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.).*";
                return hostname.matches(privateIPPattern);
            });
            conn.connect();

            // 获取服务端证书链
            Certificate[] certs = conn.getServerCertificates();
            for (Certificate cert : certs) {
                if (cert instanceof X509Certificate) {
                    X509Certificate x509Cert = (X509Certificate) cert;

                    // 获取证书的主体信息并提取 CN
                    String subject = x509Cert.getSubjectX500Principal().getName();
                    String cn = getCommonName(subject);
                    System.out.println("CN: " + cn);

                    // 获取 Subject DN（可能包含 Common Name）
                    String subjectDN = x509Cert.getSubjectDN().getName();
                    System.out.println("Subject DN: " + subjectDN);

                    // 获取 Subject Alternative Names（SAN）
                    Collection<List<?>> altNames = x509Cert.getSubjectAlternativeNames();
                    if (altNames != null) {
                        for (List<?> altNameEntry : altNames) {
                            Integer type = (Integer) altNameEntry.get(0);
                            String altName = (String) altNameEntry.get(1);
                            // 类型为 2 的是 DNS 名称
                            if (type == 2) {
                                System.out.println("Subject Alternative Name (DNS): " + altName);
                            }
                        }
                    }
                }
            }

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 从主体信息中提取 CN
    private static String getCommonName(String subject) {
        String[] parts = subject.split(",");
        for (String part : parts) {
            String trimmedPart = part.trim();
            if (trimmedPart.startsWith("CN=")) {
                return trimmedPart.substring(3);
            }
        }
        return null;
    }
}
